const Koa = require('koa');
const app = new Koa();
const router = require('koa-router')();
const compress = require('koa-compress')
const json = require('koa-json');
const onerror = require('koa-onerror');
const koaBody = require('koa-body');
const config = require('./api/config');
const wechat = require('./api/routes/wechat');
const routes = require('./api/routes');
const filter = require('./api/routes/filter');
const session = require('koa-generic-session');
const redisStore = require('koa-redis');
const path = require('path');
const fs = require('fs');
app.use(koaBody({ multipart: true,jsonLimit: '10kb'}));

const axios = require('axios');
axios.defaults.timeout = 25000;
axios.defaults.headers.common['Content-Type'] = 'application/json;charset=UTF-8';
axios.defaults.headers.common['user-agent'] = 'web/web-wechat';
axios.defaults.headers.common['connection'] = 'keep-alive';

onerror(app);

app.use(compress({
  filter: function (content_type) {
  	return /(text|javascript|css)/i.test(content_type)
  },
  threshold: 2048,
  flush: require('zlib').Z_SYNC_FLUSH
}));

app.use(json());

app.use(require('koa-static')(__dirname + '/public'));
app.use(require('koa-static')(__dirname + '/verify'));

if (process.env.NODE_ENV != 'production') {
  const cors = require('koa-cors');//跨域中间件
  app.use(cors({
    methods: ['GET', 'POST', 'PUT', 'OPTIONS'],
    credentials: true,
    Origin: '*'
  }));//设置跨域
}
app.keys = ['bsp-web-wechat', 'bsp'];
app.use(session({
  key: "bsp-web-wechat",
  store: redisStore({
    host: config.sessionRedis.host,
    port: config.sessionRedis.port,
    ttl: 1000 * 60 * 60,
  }),
  resave: true, // don't save session if unmodified
  saveUninitialized: false, // don't create session until something stored
  secret: "shengjing360",
  ttl: 60 * 60 * 1000, //session过期时间
  rolling: true, //刷新session
  cookie: {
    maxAge: null,
    overwrite: true,
    signed: true 
  } 
}));

app.use( async (ctx, next) => {
  console.log(ctx.request.url);
  const url = ctx.request.url.toUpperCase();
  if (url.indexOf(config.apiRoot.toUpperCase()) < 0 && url.indexOf(config.wechatRoot.toUpperCase()) < 0) {
    const index = path.join(__dirname, 'public', 'index.html');
    ctx.type = 'text/html;charset=utf-8'
    ctx.body = fs.createReadStream(index);
  } else {
    await next();
  }
})

router.use(config.wechatRoot, wechat.routes(), wechat.allowedMethods());
router.use(config.apiRoot, routes.routes(), routes.allowedMethods());
app.use(router.routes(), router.allowedMethods());

app.use(async (ctx) => {
  ctx.status = 404
  ctx.body = {
    status: 404,
    message: 'Api not found.'
  };
})

app.on('error', async (err, ctx) => {
  ctx.status = 500
  ctx.body = {
    status: 500,
    message: 'Sever Error',
    data: err
  };
});

module.exports = app;